package com.leyou.cat.service.impl;

import com.leyou.auth.inter.pojo.UserInfo;
import com.leyou.cat.entity.Cart;
import com.leyou.cat.interceptor.LoginInterceptor;
import com.leyou.cat.service.CartService;
import com.leyou.common.bean.Constant;
import com.leyou.common.bean.Result;
import com.leyou.common.util.JsonUtils;
import com.leyou.item.inter.api.IGoodsService;
import com.leyou.item.inter.pojo.Sku;
import com.leyou.order.inter.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zqq
 * @ClassName CartServiceImpl
 * @Description
 * @date 2020/3/10-15:01
 */
@Component
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IGoodsService iGoodsService;

    @Override
    public Result addCart(Cart cart) {
        // 获取登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        // Redis的key
        String key = Constant.KEY_CART_CODE + user.getId();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        // 判断当前商品在购物车中是否存在
        Boolean boo = hashOps.hasKey(skuId.toString());
        if (boo) {
            // 存在，获取购物车数据
            String json = hashOps.get(skuId.toString()).toString();
            cart = JsonUtils.parse(json, Cart.class);
            // 修改购物车数量
            cart.setNum(cart.getNum() + num);
        } else {
            // 不存在，新增购物车数据
            cart.setUserId(user.getId());
            // 其它商品信息，需要查询商品服务
            Result<Sku> skuResult = this.iGoodsService.querySkuById(skuId);
            if(!skuResult.success())
                return skuResult;
            Sku sku = skuResult.getData();
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
        }
        // 将购物车数据写入redis
        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
        return Result.newSuccess();
    }

    @Override
    public Result<List<Cart>> queryCartList() {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();

        // 判断是否存在购物车
        String key = Constant.KEY_CART_CODE + user.getId();
        if(!this.redisTemplate.hasKey(key)){
            // 不存在，直接返回
            return Result.newSuccess();
        }
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        List<Object> carts = hashOps.values();
        // 判断是否有数据
        if(CollectionUtils.isEmpty(carts)){
            return Result.newSuccess();
        }
        // 查询购物车数据
        List<Cart> cartList = carts.stream().map(o -> JsonUtils.parse(o.toString(), Cart.class)).collect(Collectors.toList());
        return Result.newSuccess(cartList);
    }

    @Override
    public Result updateCarts(Cart cart) {
        // 获取登陆信息
        UserInfo userInfo = LoginInterceptor.getLoginUser();
        String key = Constant.KEY_CART_CODE + userInfo.getId();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(key);
        // 判断当前商品在购物车中是否存在
        Boolean boo = hashOperations.hasKey(cart.getSkuId().toString());
        if (boo) { //存在
            // 获取购物车信息
            String cartJson = hashOperations.get(cart.getSkuId().toString()).toString();
            Cart cart1 = JsonUtils.parse(cartJson, Cart.class);
            // 更新数量
            cart1.setNum(cart.getNum());
            // 写入购物车
            hashOperations.put(cart.getSkuId().toString(), JsonUtils.serialize(cart1));
        }else{
            // 不存在，新增购物车数据
            cart.setUserId(userInfo.getId());
            // 其它商品信息，需要查询商品服务
            Result<Sku> skuResult = this.iGoodsService.querySkuById(cart.getSkuId());
            if(!skuResult.success())
                return skuResult;
            Sku sku = skuResult.getData();
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
            // 写入购物车
            hashOperations.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
        }
        return Result.newSuccess();
    }

    @Override
    public Result deleteCart(String skuId) {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        String key = Constant.KEY_CART_CODE + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        hashOps.delete(skuId);
        return Result.newSuccess();
    }

    @Override
    public Result mergeCart(List<Cart> cartList) {
        // 获取登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();
        // Redis的key
        String key = Constant.KEY_CART_CODE + user.getId();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        Map<String,String> result = new HashMap<>();
        for (Cart cart : cartList) {
            // 判断当前商品在购物车中是否存在
            Boolean boo = hashOps.hasKey(cart.getSkuId().toString());
            if (boo) {
                // 存在，获取购物车数据
                String json = hashOps.get(cart.getSkuId().toString()).toString();
                Cart cartNew = JsonUtils.parse(json, Cart.class);
                // 修改购物车数量
                cartNew.setNum(cartNew.getNum() + cart.getNum());
                result.put(cart.getSkuId().toString(),JsonUtils.serialize(cartNew));
            } else {
                // 不存在，新增购物车数据
                cart.setUserId(user.getId());
                // 其它商品信息，需要查询商品服务
                Result<Sku> skuResult = this.iGoodsService.querySkuById(cart.getSkuId());
                if(!skuResult.success())
                    return skuResult;
                Sku sku = skuResult.getData();
                cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
                cart.setPrice(sku.getPrice());
                cart.setTitle(sku.getTitle());
                cart.setOwnSpec(sku.getOwnSpec());
                result.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));
            }
        }
        if(result.size() > 0){
            // 将购物车数据写入redis
            hashOps.putAll(result);
        }
        return Result.newSuccess();
    }

    @Override
    public void clearCart(Map<String, Object> params) {
        String key = Constant.KEY_CART_CODE + params.get("userId");
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        List<OrderDetail> details = (List<OrderDetail>) params.get("detail");
        details.forEach(detail -> {
            Long skuId = detail.getSkuId();
            int num = detail.getNum();
            // 判断当前商品在购物车中是否存在
            Boolean boo = hashOps.hasKey(skuId.toString());
            if (boo) {
                // 存在，获取购物车数据
                String json = hashOps.get(skuId.toString()).toString();
                Cart cart = JsonUtils.parse(json, Cart.class);
                //如果购物车数量相等就删除，否侧就跟新
                if(cart.getNum() == num){
                    hashOps.delete(skuId);
                }else{
                    // 修改购物车数量
                    cart.setNum(cart.getNum() - num);
                    // 将购物车数据写入redis
                    hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
                }
            }
        });
    }
}
